package com.iss.umservice.controller;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.iss.iframework.common.cfg.support.ISSSystemConfig;
import com.iss.iframework.security.OperatorUserEntry;
import com.iss.iframework.web.ResultCall;
import com.iss.iframework.web.support.tld.pagination.Navigation;
import com.iss.iframework.web.support.tld.pagination.PageUtil;
import com.iss.iframework.web.support.tld.pagination.Pagination;
import com.iss.umservice.bean.CompanyApplyBean;
import com.iss.umservice.bean.CompanyBean;
import com.iss.umservice.bean.UserAccount;
import com.iss.umservice.common.SqlDatePropertyEditor;
import com.iss.umservice.manager.AccountManager;
import com.iss.umservice.manager.CompanyManager;

/**
 * 企业信息相关
 * 
 * @author luzi
 * 
 */
@Controller
@RequestMapping("/company/*")
@SessionAttributes("curUser")
public class CompanyController {
	@Autowired
	private CompanyManager companyManager;
	@Autowired
	private AccountManager accountManager;

	@RequestMapping
	public void downCompanyReport(HttpServletResponse response) {
		HSSFWorkbook workbook = new HSSFWorkbook();// 创建一个Excel文件
		HSSFCellStyle dateStyle = workbook.createCellStyle();
		dateStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFSheet sheet = workbook.createSheet();// 创建一个Excel的Sheet
		// Sheet样式
		HSSFCellStyle sheetStyle = workbook.createCellStyle();
		// 背景色的设定
		sheetStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
		// 前景色的设定
		sheetStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
		// 填充模式
		sheetStyle.setFillPattern(HSSFCellStyle.FINE_DOTS);

		// 创建列头
		createRow(sheet,0, new String[] { "企业名称", "产业类型", "办公用房", "办公用房面积(平方米)",
				"企业状态", "企业网址", "组织机构代码", "工商注册证号", "注册登记日期", "注册资本(万元)",
				"注册类型", "入驻日期", "负责人姓名", "负责人电话", "负责人信箱", "行政负责人姓名",
				"行政负责人电话", "行政负责人信箱", "财务负责人姓名", "财务负责人电话", "财务负责人信箱", "关键字",
				"备注" });
		// 创建内容
		List<CompanyBean > cs =companyManager.allCompany();
		for (int i = 0,j=1 ; i<cs.size();i++) {
			CompanyBean t  = cs.get(i);
			if (t.getCompanystatus() != 6) {
				createRow(
						sheet,j,
						new String[] { d2s(t.getCompanyname()),
								d2s(t.getCompanytype()),
								d2s(t.getOfficelocation()),
								d2s(t.getOfficesize()),
								d2sForStatus(t.getCompanystatus()), d2s(t.getCompanyweburl()), d2s(t.getOrgid()),
								d2s(t.getCompanyid()), d2s(t.getEstablishdate()), d2s(t.getRegistercapital()), d2sForApplyType(t.getApplytype()),d2s(t.getResidentdate()),
								d2s(t.getOwnername()), d2s(t.getOwnertelphone()), d2s(t.getOwneremail()), d2s(t.getAdminownername()),
								 d2s(t.getAdminownertelphone()), d2s(t.getAdminowneremail()), d2s(t.getFinancecontact()), d2s(t.getFinancecontactphone()),
								 d2s(t.getFinancecontactemail()), d2s(t.getKeyword()), d2s(t.getRemark()) });
				j++;
			}
		}

		//
		String filename = "Company Info.xls";// 设置下载时客户端Excel的名称
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename="
				+ filename);
		try {
			OutputStream ouputStream = response.getOutputStream();
			workbook.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private String d2sForApplyType(Integer applyType){
		if(applyType == null)
			return "";
		String re;
		switch(applyType){
			case 1:re= "新注册";break;
			case 2:re= "变更注册";break;
			case 3:re= "核名中";break;
			case 4:re= "拟注册";break;
			case 5:re= "拟变更注册";break;
			case 6:re= "已核名";break;
			default:throw new RuntimeException("wrong status " + applyType);
		}
		return re;
	}
	private String d2sForStatus(Integer status){
		if(status == null)
			return "";
		String re;
		switch(status){
			case 1:re= "场外";break;
			case 3:re= "入驻";break;
			case 4:re= "毕业";break;
			case 5:re= "撤出";break;
			case 6:re= "删除";break;
			default:throw new RuntimeException("wrong status " + status);
		}
		return re;
	}

	private String d2s(Object data) {
		if (data == null)
			return "";
		if (data instanceof String)
			return (String) data;
		else if (data instanceof Float) {
			return "" + data;
		}else if (data instanceof Integer) {
			return "" + data;
		}else if (data instanceof Long) {
			return "" + data;
		}else if (data instanceof Double) {
			return "" + data;
		}else if (data instanceof java.sql.Date) {
			DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
			return fmt.format(new java.util.Date(((java.sql.Date)data).getTime()));
		}
		throw new RuntimeException("wrong type " + data);
	}

	private void createRow(HSSFSheet sheet,int rowNum, String[] cols) {
		HSSFRow row = sheet.createRow(rowNum);
		//
		for (int i = 0; i < cols.length; i++) {
			HSSFCell cell0 = row.createCell((short) i);
			cell0.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell0.setCellValue(cols[i]);
		}
	}
	
	/**
	 * 从配置文件中读取产业类型
	 * @return
	 */
	private String[] industrys(){
		ISSSystemConfig xml = ISSSystemConfig.newInstance();
		String val = xml.getModuleNodeValue("industrys");
		String [] re = val.split("\n\t");
//		for (int i = 0; i < length; i++) {
//			Node node = nodeList.item(i);
//			re[i]=node.getNodeValue();
//		}
		return re;
	}

	@RequestMapping
	public String companyApplyInfo(int id, Map<String, Object> model) {
		CompanyApplyBean comp = new CompanyApplyBean();
		comp.setId(id);
		comp = companyManager.getCompanyApply(comp);
		CompanyBean comp2 = new CompanyBean();
		comp2.setId(comp.getApplyupdatecompid());
		comp2 =companyManager.getCompany(comp2);
		
		model.put("company2", comp);
		model.put("company", comp2);
		return "company/companyApplyInfo";

	}

	@RequestMapping
	public String gotoCompanyApply_mod(int id, HttpSession session,
			Map<String, Object> model) {
		CompanyBean comp = new CompanyBean();
		comp.setId(id);
		session.setAttribute("willModCompIdForApply", id);
		comp = companyManager.getCompany(comp);
		model.put("company", comp);
		model.put("industrys", industrys());
		return "company/updateCompanyInfoWithApply";

	}

	@RequestMapping
	public String companyApply_mod(
			@ModelAttribute("curUser") OperatorUserEntry userEntry,
			CompanyApplyBean bean, HttpSession session,
			Map<String, Object> model) {
		String currUserId = userEntry.extendsInfo().get("user.accountCode")
				.get(0);

		int compId = (Integer) session.getAttribute("willModCompIdForApply");
		bean.setApplyuserid(currUserId);
		bean.setApplydesc("申请修改企业信息");
		bean.setApplyupdatecompid(compId);
		bean.setApplystatus(2);
		bean.setApplydate(new java.sql.Date(System.currentTimeMillis()));

		companyManager.addCompanyApply(bean);
		bean.setId(compId);
		model.put("company", bean);
		return "company/companyInfo";

	}

	/**
	 * 同意审批
	 * 
	 * @param applyId
	 */
	@RequestMapping
	public void modCompanyApplyToOk(int applyId) {
		companyManager.modCompanyApplyToOk(applyId);
		ResultCall.makeSuccess("../company/queryCompanyApplyList.html");
	}

	/**
	 * 拒绝审批
	 * 
	 * @param applyId
	 */
	@RequestMapping
	public void modCompanyApplyToCansel(int applyId) {
		companyManager.modCompanyApplyToCansel(applyId);
		ResultCall.makeSuccess("../company/queryCompanyApplyList.html");
	}

	@RequestMapping
	public String queryCompanyApplyList(CompanyApplyBean compApply,
			String pages, Map<String, Object> model) {
		if (compApply == null) {
			compApply = new CompanyApplyBean();
			compApply.setApplystatus(2);
		} else if (compApply.getApplystatus() == null) {
			compApply.setApplystatus(2);
		}

		int count = companyManager.countCompanyApply(compApply);

		Pagination pagination = PageUtil.createPage(pages, count,
				"../company/queryCompanyApplyList.html");

		List<CompanyApplyBean> companyList = companyManager.queryCompanyapplys(
				compApply, pagination.getOffset(), pagination.getRowSize());

		model.put("companyApply", compApply);
		model.put("companyApplyList", companyList);
		model.put(Navigation.PAGINATION, pagination);

		return "company/companyApplyList";
	}

	/**
	 * 查看企业信息
	 * 
	 * @param id
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping
	public String companyInfo(int id,CompanyBean company,String pages, Map<String, Object> model) throws UnsupportedEncodingException {
		if( company.getCompanyname()!=null&&company.getCompanyname().equals(new String( company.getCompanyname().getBytes("ISO8859_1"),"ISO8859_1")))
		{
			 company.setCompanyname(new String( company.getCompanyname().getBytes("ISO8859_1"),"UTF-8"));
		}
		
		if(company.getKeyword()!=null&&company.getKeyword().equals(new String(company.getKeyword().getBytes("ISO8859_1"),"ISO8859_1")))
		{
			company.setKeyword(new String(company.getKeyword().getBytes("ISO8859_1"),"UTF-8"));
		}
		
		if(company.getCompanytype()!=null&&company.getCompanytype().equals(new String(company.getCompanytype().getBytes("ISO8859_1"),"ISO8859_1")))
		{
			company.setCompanytype(new String(company.getCompanytype().getBytes("ISO8859_1"),"UTF-8"));
		}
		CompanyBean comp = new CompanyBean();
		comp.setId(id);
		comp = companyManager.getCompany(comp);
		model.put("company", comp);
		model.put("companyname", company.getCompanyname());
		model.put("companystatus", company.getCompanystatus());
		model.put("keyword", company.getKeyword());
		model.put("companytype", company.getCompanytype());
		model.put("pages",pages);
		return "company/companyInfo";
	}

	/**
	 * 查看企业信息
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping
	public String companyInfoByComp(
			@ModelAttribute("curUser") OperatorUserEntry userEntry,
			Map<String, Object> model) {
		UserAccount userAccount = accountManager
				.queryUserAccountByUserCode(userEntry.extendsInfo()
						.get("user.accountCode").get(0));
		String currUserId = userEntry.extendsInfo().get("user.accountCode")
				.get(0);
		//
		CompanyBean comp = new CompanyBean();
		comp.setId(Integer.parseInt(userAccount.getCompanyId()));
		comp = companyManager.getCompany(comp);
		model.put("company", comp);
		return "company/companyInfo";
	}

	@RequestMapping
	public String queryCompanyList(
			@ModelAttribute("curUser") OperatorUserEntry userEntry,
			CompanyBean company, String pages, Map<String, Object> model) throws UnsupportedEncodingException {
		

		if( company.getCompanyname()!=null&&company.getCompanyname().equals(new String( company.getCompanyname().getBytes("ISO8859_1"),"ISO8859_1")))
		{
			 company.setCompanyname(new String( company.getCompanyname().getBytes("ISO8859_1"),"UTF-8"));
		}
		
		if(company.getKeyword()!=null&&company.getKeyword().equals(new String(company.getKeyword().getBytes("ISO8859_1"),"ISO8859_1")))
		{
			company.setKeyword(new String(company.getKeyword().getBytes("ISO8859_1"),"UTF-8"));
		}
		
		if(company.getCompanytype()!=null&&company.getCompanytype().equals(new String(company.getCompanytype().getBytes("ISO8859_1"),"ISO8859_1")))
		{
			company.setCompanytype(new String(company.getCompanytype().getBytes("ISO8859_1"),"UTF-8"));
		}
		int count = companyManager.countCompany(company);

		Pagination pagination = PageUtil.createPage(pages, count,
				"../company/queryCompanyList.html");

		List<CompanyBean> companyList = companyManager.queryCompanys(company,
				pagination.getOffset(), pagination.getRowSize());

		pagination.addCondition("companyname", company.getCompanyname());
		pagination.addCondition("companystatus", company.getCompanystatus());
		pagination.addCondition("keyword", company.getKeyword());
		pagination.addCondition("companytype", company.getCompanytype());	
		model.put("offset", pagination.getOffset());
		model.put("company", company);
		model.put("companyList", companyList);
		model.put("industrys", industrys());
		model.put(Navigation.PAGINATION, pagination);
		model.put("companyname", company.getCompanyname());
		model.put("companystatus", company.getCompanystatus());
		model.put("keyword", company.getKeyword());
		model.put("companytype", company.getCompanytype());
		model.put("pages",pages);

		return "company/companylist";
	}

	/**
	 * 跳转界面
	 * 
	 * @return
	 */
	@RequestMapping
	public void insertCompanyInfo(Map<String, Object> model) {
		model.put("industrys", industrys());
	}

	@RequestMapping
	public void addCompanyInfo(CompanyBean newComp) {
		companyManager.addCompany(newComp);
		ResultCall.makeSuccess("../company/queryCompanyList.html");
	}

	/**
	 * 校验名称是否已存在
	 */
	@RequestMapping
	public void checkCompanyName(Integer id, String companyname,
			HttpServletResponse response) throws UnsupportedEncodingException {
		companyname = URLDecoder.decode(companyname, "UTF-8");
		String isExist = "0";
		for (CompanyBean c : companyManager.allCompany()) {
			if (c.getCompanyname().equals(companyname)) {
				if (id == null || c.getId() != id) {
					if (c.getCompanystatus() != null
							&& c.getCompanystatus() != 6) {
						isExist = "1";
						break;
					}
				}
			}
		}

		PrintWriter writer = null;
		try {
			response.setCharacterEncoding("UTF-8");
			writer = response.getWriter();
			writer.write(isExist);
		} catch (Exception e) {
		}
	}

	@RequestMapping
	public String gotoModCompanyInfo(int id,CompanyBean company, String pages,Map<String, Object> model,
			HttpSession session) throws UnsupportedEncodingException {
		session.setAttribute("willModCompId", id);
		CompanyBean comp = new CompanyBean();
		comp.setId(id);	
		comp = companyManager.getCompany(comp);
		model.put("company", comp);
		model.put("industrys", industrys());
		if(company.getCompanyname()!=null)
		{
		model.put("companyname", new String(company.getCompanyname().getBytes("ISO8859_1"),"UTF-8"));
		}
		model.put("companystatus", company.getCompanystatus());
		if(company.getKeyword()!=null)
		{
		model.put("keyword", new String(company.getKeyword().getBytes("ISO8859_1"),"UTF-8"));
		}
		if(company.getCompanytype()!=null)
		{
		model.put("companytype",new String(company.getCompanytype().getBytes("ISO8859_1"),"UTF-8"));
		}
		model.put("pages",pages);

		return "company/updateCompanyInfo";
	}

	@RequestMapping
	public void modCompanyInfo(CompanyBean comp,String companyname1,String companystatus1,String keyword1,String companytype1,String pages,HttpSession session) throws UnsupportedEncodingException {
		comp.setId((Integer) session.getAttribute("willModCompId"));
		companyManager.modCompany(comp);
		if(companyname1!=null)
		{
			companyname1 = new String(companyname1.getBytes("ISO8859_1"),"UTF-8");
		}
		
		if(keyword1!=null)
		{
			keyword1 = new String(keyword1.getBytes("ISO8859_1"),"UTF-8");
		}
		
		if(companytype1!=null)
		{
			companytype1 = new String(companytype1.getBytes("ISO8859_1"),"UTF-8");
		}
		ResultCall.makeSuccess("../company/queryCompanyList.html?companyname="+companyname1+"&companystatus="+companystatus1+"&keyword="+keyword1+"&companytype="+companytype1+"&pages="+pages);
	}

	@RequestMapping
	public void delCompanys(int[] deleteIds) {
		companyManager.discardCompany(deleteIds);
		ResultCall.makeSuccess("../company/queryCompanyList.html");
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) throws Exception {
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		SqlDatePropertyEditor dateEditor = new SqlDatePropertyEditor(fmt, true);
		binder.registerCustomEditor(Date.class, dateEditor);
	}
}